/**
 * 证件换发流程
 * 1. 发起证件换发上报流程
 * 2. 上报成功后修改原有证件状态为“证件换发中”
 * 原有的证件需要进入证件换发状态中
 * 生成一条新的数据，证件状态是处于已提交，待审核状态
 * 发起流程
 */
function main() {
    const self = this;
    const formPartEle = this.$$element("form_part_fc3b7f");
    const documentNo = formPartEle.$$getRenderElement().getDocumentNo();
    const nowTime = formPartEle.$$("date_picker_7gk1mj").$$getValue();

    formPartEle.$$getRenderElement().onSave()
        .then(() => {
            const params = [{ name: "ids", valueContent: documentNo }];
            return getApiValue(params);
        })
        .then(data => {
            const result = data.result;
            const updatedFields = prepareCertificateData(result, nowTime);
            const insertStatement = generateInsertStatement(updatedFields);
            console.log("插入语句:", insertStatement);

            return api.EXEC_FORMULA(insertStatement);
        })
        .then(() => {
            const selectQuery = `ENTITY_SELECT_ONE('t_ecdf9c71ff624a45a65adb0ece7a64a8', id, QUERY_AND(QUERY_EQ('identity_no', '${result.identity_no}'), QUERY_EQ('create_time', '${nowTime}')))`;
            return api.EXEC_FORMULA(selectQuery);
        })
        .then(res => {
            console.log("新增数据:", res.result);
            const cardRenewalDocumentNo = res.result;
            const updateQuery = `UPDATE('t_ecdf9c71ff624a45a65adb0ece7a64a8', QUERY_EQ('id', '${cardRenewalDocumentNo}'), '', ['documentNo', '${cardRenewalDocumentNo}', 'card_status_code', '14', 'card_status_name', '证件换发中'])`;
            return api.EXEC_FORMULA(updateQuery).then(() => cardRenewalDocumentNo);
        })
        .then(cardRenewalDocumentNo => {
            confirmAndSubmit(self, cardRenewalDocumentNo);
        })
        .catch(error => {
            console.error("证件换发流程出错:", error);
            self.$message.error("操作失败，请稍后重试");
        });
}

/**
 * 准备证件数据
 * @param {Object} result - API 返回的证件数据
 * @param {string} nowTime - 当前时间
 * @returns {Object} 更新后的字段对象
 */
function prepareCertificateData(result, nowTime) {
    const fields = {
        rollback_flag: null,
        apply_human_name: null,
        qualification_apply_human_name: null,
        qualification_apply_human_id: null,
        apply_human_id: null,
        certificate_validity_time_end: null,
        law_major_flag: null,
        card_type_code: null,
        card_status_code: 1, // 待审核
        law_qualification_flag: null,
        business_institution: null,
        law_enforcement_duties: null,
        card_type_name: null,
        valid_flag: null,
        remark: null,
        litigant_type_id: null,
        issue_certificate_time: null,
        identity_no: null,
        card_code: null,
        update_time: null,
        effective_date: null,
        illegal_history: null,
        law_region_code: null,
        exam_time: null,
        law_area_name: null,
        law_area_code: null,
        enforcement_type_code: null,
        delete_flag: null,
        enforcement_category_name: null,
        law_enforcement_post: null,
        enforcement_type_name: null,
        law_region_name: null,
        work_status_name: null,
        business_institution_code: null,
        qualification_update_time: null,
        qualification_name: null,
        rank_code: null,
        public_lawyer_flag: null,
        certificate_validity_time_start: null,
        enforcement_category_code: null,
        qualification_code: null,
        card_status_name: "待审核",
        work_status_code: null,
        litigant_type_name: null,
        create_time: nowTime,
        certificate_time: null,
        qualification_certificate_flag: null,
        phone: null,
        human_name: null,
        professional_law_scores: null,
        apply_human_unit_id: null,
        apply_human_unit_name: null,
        apply_human_region_id: null,
        apply_human_region_name: null,
        apply_human_region_level: null,
        renewal_flag: 1 // 表示换发
    };

    return Object.assign({}, fields, result);
}

/**
 * 生成插入语句
 * @param {Object} fields - 字段键值对
 * @returns {string} 插入语句
 */
function generateInsertStatement(fields) {
    const keyValuePairs = Object.entries(fields)
        .map(([key, value]) => `'${key}', ${JSON.stringify(value)}`)
        .join(", ");
    //const insertStatement = `INSERT("t_ecdf9c71ff624a45a65adb0ece7a64a8", [${keyValuePairs}]);`;
    //
    //                     console.log(insertStatement);
    return `INSERT("t_ecdf9c71ff624a45a65adb0ece7a64a8", [${keyValuePairs}]);`;
}

/**
 * 弹出确认框并提交流程
 * @param {Object} self - 当前上下文
 * @param {string} documentNo - 证件编号
 */
function confirmAndSubmit(self, documentNo) {
    self.$lc_Confirm({
        content: "确定发起证件换发上报流程？",
        type: "info",
        headerTitle: "提示",
        showOkBtn: true,
        showCancelBtn: true,
        cancelText: "取消",
        okText: "确定",
        onOk: () => {
            submitProcess(self, documentNo)
                .then(res => {
                    if (res && res.result) {
                        self.$message.success("提交成功！");
                        notifyParentAndClose(self);
                    }
                })
                .catch(err => {
                    console.error("提交流程失败:", err);
                    self.$message.error("提交失败");
                });
        },
        onCancel: () => {
            console.log("取消操作");
        }
    });
}

/**
 * 通知父窗口并关闭对话框
 * @param {Object} self - 当前上下文
 */
function notifyParentAndClose(self) {
    const pageRenderElement = self.$$root().$parent.$parent.$parent;
    if (window.parent) {
        window.parent.postMessage(
            JSON.stringify({ event: "close-dialog", param: { XXX: "test" } }),
            "*"
        );
    }
    pageRenderElement.goHistory(-1);
}

/**
 * 获取 API 数据
 * @param {Array} params - 请求参数
 * @returns {Promise<Object>} API 返回结果
 */
function getApiValue(params) {
    return api.DATA_SOURCE_EXECUTE(
        "bbfafac8-91c5-4829-9d1e-c189e001ebef",
        "api",
        params,
        [],
        ""
    ).then(res => JSON.parse(res.result));
}

/**
 * 提交流程
 * @param {Object} self - 当前上下文
 * @param {string} documentNo - 证件编号
 * @returns {Promise<Object>} 提交结果
 */
function submitProcess(self, documentNo) {
    const queryParams = [{ name: "pageId", valueContent: "4d080a08-d4d1-4490-86e4-139d7aa0a3dd" }];
    const jsonParams = { documentNo };
    return api.DATA_SOURCE_EXECUTE(
        "a2b29830-9ef5-437a-8975-476783d4e73f",
        "api",
        queryParams,
        [],
        JSON.stringify(jsonParams)
    ).then(res => {
        if (res.hasError) throw new Error(res.message);
        return res;
    });
}
